import router from '../route'
import axios from 'axios'
import {storage} from './storage'
import {ElMessage,ElMessageBox} from "element-plus";
// @ts-ignore
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API as string,
})


instance.interceptors.request.use(
    (config) => {
        NProgress.start()
        const token = storage('token').get()
        if (token) {
            // const newConfig = {...config}
            config.headers['x-access-token'] = `${token}`
        }
        return config
    },
    (error) => Promise.reject(error)
)
let isRefreshing = false
instance.interceptors.response.use(
    (response) => {
        NProgress.done()
        const status = response.status
        const res = response.data
        if (!status || status === 200) {
            if(res.code!==200){
                ElMessage.error(res.message || '请求失败，请稍后重试')
            }
            return response.data
        }
        if (isRefreshing) return Promise.reject(response)

        ElMessage.error(response.data.msg || '请求失败，请稍后重试')
        return Promise.reject(response.data)
    }, error => {
        NProgress.done()
        const status = error.status
        const res = error.data
        if (status === 401) {
            ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                storage('token').remove()
                storage('username').remove()
                router.push({
                    path: '/login',
                    query: {
                        redirect: router.currentRoute.value.fullPath
                    }
                })
            }).catch(() => {
                ElMessage.error(res.message || '请求异常')
            }).finally(() => {
                isRefreshing = false
            })
        }
        return Promise.reject(error)
    }
)
export default instance;